package com.mialab.servlet_demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mialab.servlet_demo.entity.Book;

@WebServlet("/RequestScopeAttrServlet")
public class RequestScopeAttrServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public RequestScopeAttrServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应的文本类型为HTML，字符编码为UTF-8
		response.setContentType("text/html;charset=UTF-8");
		// 在request范围内设置名为book的Book对象属性
		request.setAttribute("book", new Book(9801, "《Android应用开发实践教程》"));
		// 在request范围内设置名为singer的String对象属性
		request.setAttribute("singer", "Jessie J，第32届全英音乐奖入围最佳女艺人，《歌手2018》总冠军");
		// 在request范围内设置名为newdate的Date对象属性
		request.setAttribute("newdate", new Date());
		// 从request范围内获取名为book的属性
		Book book = (Book) request.getAttribute("book");
		// 从request范围内获取名为singer的属性
		String singer = (String) request.getAttribute("singer");
		// 从request范围内获取名为newdate的属性
		Date date = (Date) request.getAttribute("newdate");
		// 获取输出流
		PrintWriter out = response.getWriter();
		out.println("<p>request.getAttribute(\"book\")的值：" + book + "</p>");
		out.println("<p>request.getAttribute(\"singer\")的值：" + singer + "</p>");
		out.println("<p>request.getAttribute(\"newdate\")的值：" + date + "</p>");

		Enumeration<String> names = request.getAttributeNames();
		out.println("<p>request请求域中的属性有：");
		while (names.hasMoreElements()) {
			out.println(names.nextElement() + "&nbsp;");
		}
		out.println("</p>");
		request.removeAttribute("book");
		out.println("<p>执行request.removeAttribute(\"book\")后request请求域中的属性有：");
		names = request.getAttributeNames();
		while (names.hasMoreElements()) {
			out.println(names.nextElement() + "&nbsp;");
		}
		out.close();

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
